#!/usr/bin/env python

import SocketServer
import commands

class MyTCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        while 1:
            self.data = self.request.recv(1024).strip()
            print "{} wrote:".format(self.client_address[0])
            if not self.data:
                print "client %s is dead!" % self.client_address[0]
                break
            print self.data
            cmd_status,cmd_result = commands.getstatusoutput(self.data)
            if len(cmd_result.strip()) != 0:
                self.request.sendall(cmd_result)
                print cmd_status 
            else:
                self.request.sendall("Done")

if __name__ == "__main__":
    HOST, PORT = "", 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()
